import { useEffect, useRef, ReactNode } from 'react'
import { ConfigProvider } from 'antd'
import { getTheme } from '@/config/theme'
import { useThemeStore } from '@/stores'

interface ThemeProviderProps {
  children: ReactNode
}

export function ThemeProvider({ children }: ThemeProviderProps) {
  const theme = useThemeStore((state) => state.theme)
  const isInitializedRef = useRef(false)

 
  useEffect(() => {
    if (!window.ipcRenderer) return

    const handleThemeChange = (_event: unknown, newTheme: 'light' | 'dark') => {
    
      const currentTheme = useThemeStore.getState().theme
    
      if (newTheme !== currentTheme) {
        useThemeStore.getState().setTheme(newTheme, true) 
      }
    }

    const handleThemeToggle = () => {
      useThemeStore.getState().toggleTheme()
    }

    window.ipcRenderer.on('theme-changed', handleThemeChange)
    window.ipcRenderer.on('theme-toggle', handleThemeToggle)

 
    if (!isInitializedRef.current) {
      const initialTheme = useThemeStore.getState().theme
      window.ipcRenderer.send('theme-init', initialTheme)
      isInitializedRef.current = true
    }

    return () => {
      window.ipcRenderer?.off('theme-changed', handleThemeChange)
      window.ipcRenderer?.off('theme-toggle', handleThemeToggle)
    }
  }, []) 

  const themeConfig = getTheme(theme)

  return (
    <ConfigProvider theme={themeConfig}>
      <div data-theme={theme}>
        {children}
      </div>
    </ConfigProvider>
  )
}

export function useTheme() {
  return useThemeStore((state) => state.theme)
}

